//import MongoClient from mongodb
import { MongoClient } from "mongodb";

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

//function insert, insert users into mongodb database
async function insert(user) {
    try {
        await client.connect();
        const database = client.db("mydb");
        const collection = database.collection("users");
        const result = await collection.insertOne(user);
        console.log(`Inserted user with id: ${result.insertedId}`);
    } finally {
        await client.close();
    }
}

//function query, query users from mongodb database with username
async function query(username) {
    try {
        await client.connect();
        const database = client.db("mydb");
        const collection = database.collection("users");
        const query = { username: username };
        const result = await collection.findOne(query);
        return result;
    } finally {
        await client.close();
    }
}

export const db = { insert, query };